<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Log Viewer</title>
    <style>
        :root {
            --primary-color: #3498db;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --light-color: #ecf0f1;
            --dark-color: #2c3e50;
            --background-color: #f5f7fa;
            --border-color: #dfe6e9;
            --shadow-color: rgba(0, 0, 0, 0.1);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: auto;
            background-color: var(--background-color);
            padding: 20px;
            color: var(--dark-color);
            line-height: 1.6;
        }

        /* 基础按钮样式 */
        #data-btn {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        /* 非活跃状态 */
        #data-btn.inactive {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        /* 悬停效果 */
        #data-btn:not(.inactive):hover {
            background-color: #45a049;
        }

        /* 加载状态 */
        #data-btn.loading {
            background-color: #2196F3;
            position: relative;
        }

        #data-btn.loading::after {
            content: "";
            position: absolute;
            width: 16px;
            height: 16px;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            border: 3px solid transparent;
            border-top-color: #ffffff;
            border-radius: 50%;
            animation: button-loading-spinner 1s ease infinite;
        }

        @keyframes button-loading-spinner {
            from { transform: rotate(0turn); }
            to { transform: rotate(1turn); }
        }
        h1 {
            color: var(--dark-color);
            text-align: center;
            margin-bottom: 30px;
            font-weight: 600;
            font-size: 2.2rem;
        }

        .controls {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 30px;
            gap: 15px;
            flex-wrap: wrap;
        }

        button {
            padding: 12px 25px;
            font-size: 16px;
            border: none;
            cursor: pointer;
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px var(--shadow-color);
        }

        button:hover:not(.inactive) {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px var(--shadow-color);
        }

        button:active:not(.inactive) {
            transform: translateY(0);
        }

        .active {
            color: white;
        }

        #connect-btn.active {
            background-color: var(--primary-color);
        }

        #disconnect-btn.active {
            background-color: var(--danger-color);
        }

        #shutdown-btn.active {
            background-color: var(--warning-color);
        }

        #submit-btn.active {
            background-color: var(--success-color);
        }

        .inactive {
            background-color: var(--light-color);
            color: #7f8c8d;
            cursor: not-allowed;
        }

        .log-container {
            height: 600px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            padding: 20px;
            background-color: white;
            color: var(--dark-color);
            box-shadow: 0 0 15px var(--shadow-color);
            border-radius: 8px;
            font-family: 'Consolas', 'Courier New', monospace;
            line-height: 1.5;
        }

        .log-entry {
            margin-bottom: 5px;
        }

        .debug {
            color: blue;
        }

        .info {
            color: green;
        }

        .warn {
            color: orange;
        }

        .error {
            color: red;
        }

        .classname {
            color: #298a8a;
        }

        /* Modal styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 10;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            width: 400px;
            max-width: 90%;
            animation: slideDown 0.4s;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .close-modal {
            float: right;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
        }

        .close-modal:hover {
            color: #555;
        }

        form {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-top: 15px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        label {
            font-weight: bold;
            margin-bottom: 8px;
            color: var(--dark-color);
        }

        input[type="text"],
        select {
            padding: 12px;
            border: 2px solid var(--primary-color);
            border-radius: 6px;
            font-size: 14px;
            box-shadow: 0 0 5px var(--shadow-color);
            transition: border-color 0.3s, box-shadow 0.3s;
        }

        input[type="text"]:focus,
        select:focus {
            outline: none;
            border-color: #2980b9;
            box-shadow: 0 0 8px rgba(52, 152, 219, 0.5);
        }

        .btn-submit {
            align-self: center;
            padding: 15px 30px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s;
            font-weight: bold;
            margin-top: 10px;
        }

        .btn-submit:hover {
            background-color: #2980b9;
            transform: translateY(-2px);
        }

        .btn-submit:active {
            transform: translateY(0);
        }

        /* Task count styles */
        .thread-count {
            margin: 20px 0;
            text-align: center;
            font-size: 18px;
            border-radius: 8px;
            background-color: white;
            padding: 15px;
            box-shadow: 0 2px 10px var(--shadow-color);
        }

        .count-value {
            font-weight: bold;
            color: var(--primary-color);
        }

        /* Toast notification */
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px 25px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            z-index: 100;
            opacity: 0;
            transition: opacity 0.3s;
            pointer-events: none;
        }

        .toast.success {
            background-color: var(--success-color);
        }

        .toast.error {
            background-color: var(--danger-color);
        }

        .toast.warning {
            background-color: var(--warning-color);
        }

        .toast.info {
            background-color: var(--primary-color);
        }

        .toast.show {
            opacity: 1;
        }

        /* Loading spinner */
        .spinner {
            display: none;
            width: 40px;
            height: 40px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top: 4px solid var(--primary-color);
            animation: spin 1s linear infinite;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000;
        }

        @keyframes spin {
            0% { transform: translate(-50%, -50%) rotate(0deg); }
            100% { transform: translate(-50%, -50%) rotate(360deg); }
        }

        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }

        /* Auto-complete list styles */
        .autocomplete-list {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid var(--border-color);
            border-top: none;
            border-radius: 0 0 6px 6px;
            max-height: 200px;
            overflow-y: auto;
            display: none;
            z-index: 100;
        }

        .autocomplete-item {
            padding: 10px;
            cursor: pointer;
        }

        .autocomplete-item:hover {
            background-color: #f1f1f1;
        }

        /* Responsive design */
        @media (max-width: 768px) {
            h1 {
                font-size: 1.8rem;
            }

            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            button {
                width: 100%;
            }
        }
        /* 优化日志容器样式 */
        .log-container {
            height: 600px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            padding: 20px;
            background-color: white;
            color: var(--dark-color);
            box-shadow: 0 0 15px var(--shadow-color);
            border-radius: 8px;
            font-family: 'Consolas', 'Courier New', monospace;
            line-height: 1.5;
            word-wrap: break-word; /* 长单词或不间断字符串自动换行 */
        }

        .log-entry {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 4px;
            word-wrap: break-word; /* 确保内容自动换行 */
        }

        /* 为日志条目添加背景色 */
        .log-entry:nth-child(odd) {
            background-color: rgba(52, 152, 219, 0.1);
        }

        .log-entry:nth-child(even) {
            background-color: rgba(46, 204, 113, 0.1);
        }

        /* 优化手机端样式 */
        @media (max-width: 768px) {
            .log-container {
                height: 400px;
                padding: 10px;
                font-size: 14px;
            }

            .log-entry {
                margin-bottom: 8px;
                padding: 6px;
            }
        }
    </style>
</head>
<body>
<h1>WebSocket Log Viewer</h1>
<div class="controls">
    <button id="connect-btn" class="inactive">打开日志</button>
    <button id="disconnect-btn" class="inactive">关闭日志</button>
    <button id="shutdown-btn" class="inactive">终止抢单</button>
    <button id="submit-btn" class="inactive">提交任务</button>
    <button id="data-btn" class="inactive">任务数据面板</button>
</div>

<div class="thread-count">
    正在运行的任务实例数量: <span id="taskCount" class="count-value">0</span>
</div>

<div id="log-container" class="log-container"></div>

<div id="toast" class="toast"></div>
<div class="overlay" id="loading-overlay"></div>
<div class="spinner" id="loading-spinner"></div>

<div id="modal" class="modal">
    <div class="modal-content">
        <span class="close-modal" id="close-modal">&times;</span>
        <h2>提交任务</h2>
        <form id="submit-form">
            <div class="form-group">
                <label for="userName">用户名：</label>
                <select id="userName" name="userName" required>
                    <option value="">-- 请选择用户 --</option>
                    <option value="TQ">田沁</option>
                    <option value="TJB">唐金彪</option>
                    <option value="HJY">何江渝</option>
                </select>
            </div>

            <div class="form-group">
                <label for="price">心理预期价格(最大值)：</label>
                <input type="text" id="price" name="price" placeholder="请输入价格" required pattern="[0-9.]+" title="请输入有效的数字">
            </div>

            <div class="form-group">
                <label for="subTypeInput">商品名称：</label>
                <div style="position: relative;">
                    <input type="text" id="subTypeInput" name="subTypeInput" placeholder="输入商品名称" required>
                    <div id="autocompleteList" class="autocomplete-list"></div>
                </div>
            </div>

            <button type="submit" class="btn-submit">提交任务</button>
        </form>
    </div>
</div>

<script>
    // DOM Elements
    const elements = {
        logContainer: document.getElementById('log-container'),
        connectBtn: document.getElementById('connect-btn'),
        disconnectBtn: document.getElementById('disconnect-btn'),
        dataBtn: document.getElementById("data-btn"),
        shutdownBtn: document.getElementById('shutdown-btn'),
        submitBtn: document.getElementById('submit-btn'),
        modal: document.getElementById('modal'),
        closeModal: document.getElementById('close-modal'),
        taskCountElement: document.getElementById('taskCount'),
        subTypeInput: document.getElementById('subTypeInput'),
        autocompleteList: document.getElementById('autocompleteList'),
        form: document.getElementById('submit-form'),
        toast: document.getElementById('toast'),
        loadingOverlay: document.getElementById('loading-overlay'),
        loadingSpinner: document.getElementById('loading-spinner')
    };

    // Configuration
    const config = {
        baseUrl: 'http://47.109.35.232:7779',
        wsUrl: 'ws://47.109.35.232:7779/websocket/logging',
        // baseUrl: 'http://localhost:7779',
        // wsUrl: 'ws://localhost:7779/websocket/logging',
        refreshInterval: 2000,
        toastDuration: 3000,
        logLimit: 1000 // Maximum number of log entries to keep
    };

    // App state
    const state = {
        socket: null,
        isConnected: false,
        runningTasks: 0,
        logEntries: [],
        intervalId: null,
        selectedGoodId: null // 存储选中的商品ID
    };
    const colors = [
        '#f8d7da', '#d1e7dd', '#fff3cd', '#d6f7ff', '#fff8e1',
        '#e2e3e5', '#e8f5e9', '#f3e5f5', '#e0f7fa', '#fffde7'
    ];


    // Initialize the application
    function initApp() {
        registerEventListeners();
        startTaskCountMonitoring();
    }
    function getRandomColor() {
        return colors[Math.floor(Math.random() * colors.length)];
    }
    // Register all event listeners
    function registerEventListeners() {
        elements.connectBtn.addEventListener('click', connectWebSocket);
        elements.disconnectBtn.addEventListener('click', disconnectWebSocket);
        elements.shutdownBtn.addEventListener('click', shutdownTasks);
        elements.dataBtn.addEventListener('click', openThePageOfData);
        elements.submitBtn.addEventListener('click', openModal);
        elements.closeModal.addEventListener('click', closeModal);
        elements.form.addEventListener('submit', submitTask);

        // 添加输入框事件监听
        elements.subTypeInput.addEventListener('input', handleSubTypeInput);

        // Close modal when clicking outside
        window.addEventListener('click', (event) => {
            if (event.target === elements.modal) {
                closeModal();
            }
        });

        // Add form validation
        elements.form.addEventListener('input', validateForm);
    }

    // Connect to WebSocket
    function connectWebSocket() {
        if (state.socket && state.socket.readyState === WebSocket.OPEN) {
            state.socket.close();
        }

        showLoading();

        try {
            state.socket = new WebSocket(config.wsUrl);

            state.socket.onopen = (event) => {
                state.isConnected = true;
                updateButtonStates();
                showToast('WebSocket 连接已打开', 'success');
                hideLoading();
            };

            state.socket.onclose = (event) => {
                state.isConnected = false;
                updateButtonStates();
                showToast('WebSocket 连接已关闭', 'info');
                hideLoading();
            };

            state.socket.onerror = (error) => {
                showToast('WebSocket 连接错误', 'error');
                console.error('WebSocket Error:', error);
                hideLoading();
            };

            state.socket.onmessage = handleLogMessage;

        } catch (error) {
            showToast('创建 WebSocket 连接失败', 'error');
            console.error('WebSocket creation error:', error);
            hideLoading();
        }
    }

    // Handle incoming log messages
    function handleLogMessage(event) {
        // Add the log message to the state
        state.logEntries.push(event.data);

        // Trim logs if they exceed the limit
        if (state.logEntries.length > config.logLimit) {
            state.logEntries = state.logEntries.slice(-config.logLimit);
        }

        // Update the display
        renderLogs();
    }

    // Render all logs efficiently
    function renderLogs() {
        // Only append the new log instead of rebuilding everything
        const lastLog = state.logEntries[state.logEntries.length - 1];

        if (lastLog) {
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            logEntry.innerHTML = lastLog;
            elements.logContainer.appendChild(logEntry);

            // Auto-scroll to the bottom
            elements.logContainer.scrollTop = elements.logContainer.scrollHeight;
        }
    }

    // Disconnect WebSocket
    function disconnectWebSocket() {
        if (state.socket) {
            state.socket.close();
            elements.logContainer.innerHTML = '';
            state.logEntries = [];
        }
    }
    // Handle incoming log messages
    function handleLogMessage(event) {
        // Add the log message to the state
        state.logEntries.push(event.data);

        // Trim logs if they exceed the limit
        if (state.logEntries.length > config.logLimit) {
            state.logEntries = state.logEntries.slice(-config.logLimit);
        }

        // Update the display
        renderLogs();
    }
    function openThePageOfData(){
        const dataBtn = document.getElementById('data-btn');
        dataBtn.addEventListener('click', function() {
            const targetUrl = '/userTaskDataIndex';

            // 显示加载状态
            // dataBtn.disabled = true;
            // dataBtn.textContent = '跳转中...';
            // dataBtn.classList.add('loading');
            window.open(targetUrl, '_blank');
        });
        dataBtn.disabled = false;
        // 初始状态激活
        dataBtn.classList.remove('inactive');
    }

    // Render all logs efficiently
    function renderLogs() {
        // Only append the new log instead of rebuilding everything
        const lastLog = state.logEntries[state.logEntries.length - 1];

        if (lastLog) {
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            logEntry.innerHTML = lastLog;

            // 为每条日志条目生成随机颜色
            const randomColor = getRandomColor();
            logEntry.style.backgroundColor = randomColor;
            logEntry.style.padding = '8px';
            logEntry.style.marginBottom = '5px';
            logEntry.style.borderRadius = '4px';

            // 根据背景色亮度调整文本颜色
            const brightness = calculateBrightness(randomColor);
            logEntry.style.color = brightness > 125 ? '#333' : '#fff';

            elements.logContainer.appendChild(logEntry);

            // Auto-scroll to the bottom
            elements.logContainer.scrollTop = elements.logContainer.scrollHeight;
        }
    }

    // 生成随机颜色
    function getRandomColor() {
        const r = Math.floor(Math.random() * 200); // 限制范围以避免过亮或过暗
        const g = Math.floor(Math.random() * 200);
        const b = Math.floor(Math.random() * 200);
        return `rgb(${r}, ${g}, ${b})`;
    }

    // 计算颜色亮度
    function calculateBrightness(color) {
        const rgb = color.match(/\d+/g);
        return (parseInt(rgb[0]) * 299 + parseInt(rgb[1]) * 587 + parseInt(rgb[2]) * 114) / 1000;
    }
    // Shutdown tasks
    function shutdownTasks() {
        if (state.runningTasks <= 0) {
            showToast('当前没有运行中的任务', 'warning');
            return;
        }

        showToast('已成功终止所有抢单任务', 'success');

        fetch(`${config.baseUrl}/shutDownThread`, { method: 'GET' });
    }

    // Open the task submission modal
    function openModal() {
        if (!state.isConnected) {
            showToast('请先连接到WebSocket', 'warning');
            return;
        }
        elements.modal.style.display = 'block';
    }

    // Close the task submission modal
    function closeModal() {
        elements.modal.style.display = 'none';
        elements.form.reset();
        elements.autocompleteList.style.display = 'none';
        state.selectedGoodId = null;
    }

    // Validate the form
    function validateForm() {
        const price = elements.form.price.value.trim();

        // Valid price format (number)
        if (price && !/^[0-9]+(\.[0-9]+)?$/.test(price)) {
            elements.form.price.setCustomValidity('请输入有效的数字');
        } else {
            elements.form.price.setCustomValidity('');
        }
    }

    // Handle商品名称输入
    function handleSubTypeInput() {
        const input = elements.subTypeInput.value.trim();
        if (input.length < 1) {
            elements.autocompleteList.style.display = 'none';
            return;
        }

        // 清空之前的自动补全列表
        elements.autocompleteList.innerHTML = '';
        elements.autocompleteList.style.display = 'none';

        showLoading();

        const controller = new AbortController();
        const signal = controller.signal;

        // 设置1秒超时
        const timeoutId = setTimeout(() => {
            if (controller.signal.aborted) return;
            controller.abort();
        }, 1000);

        fetch(`${config.baseUrl}/searchDataByName?name=${encodeURIComponent(input)}`, { signal })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // 确保返回的数据是数组
                if (!Array.isArray(data)) {
                    throw new Error('Invalid data format');
                }

                if (data.length === 0) {
                    const noResult = document.createElement('div');
                    noResult.className = 'autocomplete-item';
                    noResult.textContent = '没有找到匹配的商品';
                    elements.autocompleteList.appendChild(noResult);
                } else {
                    data.forEach(item => {
                        const option = document.createElement('div');
                        option.className = 'autocomplete-item';
                        option.textContent = item.goodName;
                        option.dataset.goodId = item.goodId;
                        option.addEventListener('click', () => {
                            elements.subTypeInput.value = item.goodName;
                            state.selectedGoodId = item.goodId;
                            elements.autocompleteList.style.display = 'none';
                        });
                        elements.autocompleteList.appendChild(option);
                    });
                }

                elements.autocompleteList.style.display = 'block';
            })
            .catch(error => {
                console.error('Error fetching product types:', error);
                showToast('加载商品类型失败', 'error');
            })
            .finally(() => {
                hideLoading();
                clearTimeout(timeoutId);
            });
    }

    // 提交任务
    function submitTask(e) {
        e.preventDefault();

        const formData = new FormData(elements.form);
        const userName = formData.get('userName');
        const price = formData.get('price');
        const goodName = formData.get('subTypeInput');
        const goodId = state.selectedGoodId;
        if (!userName || !price || !goodId || !goodName) {
            showToast('所有字段都必须填写', 'warning');
            return;
        }

        showToast('本次锁单任务提交成功', 'success');
        closeModal();

        const url = `${config.baseUrl}/buyXmData?userName=${encodeURIComponent(userName)}&price=${encodeURIComponent(price)}&goodName=${encodeURIComponent(goodName)}&subType=${encodeURIComponent(goodId)}`;

        const controller = new AbortController();
        setTimeout(() => controller.abort(), 10000); // 设置10秒超时，如果需要的话

        fetch(url, { signal: controller.signal });
    }

    // Start monitoring the task count
    function startTaskCountMonitoring() {
        if (state.intervalId) {
            clearInterval(state.intervalId);
        }

        updateTaskCount();
        state.intervalId = setInterval(updateTaskCount, config.refreshInterval);
    }

    // Update the task count display
    function updateTaskCount() {
        fetch(`${config.baseUrl}/getRunningThreadCount`)
            .then(response => response.json())
            .then(data => {
                const count = Object.values(data)[0];
                state.runningTasks = count;
                elements.taskCountElement.textContent = count;
                updateButtonStates();
            })
            .catch(error => {
                console.error('Error fetching task count:', error);
            });
    }

    // Update button states based on current app state
    function updateButtonStates() {
        // Connect button
        if (state.isConnected) {
            elements.connectBtn.classList.add('active');
            elements.connectBtn.classList.remove('inactive');
        } else {
            elements.connectBtn.classList.remove('active');
            elements.connectBtn.classList.add('inactive');
        }

        // Disconnect button
        if (state.isConnected) {
            elements.disconnectBtn.classList.remove('inactive');
            elements.disconnectBtn.classList.add('active');
            elements.dataBtn.classList.remove('inactive');
            elements.dataBtn.classList.add('active');
        } else {
            elements.disconnectBtn.classList.add('inactive');
            elements.disconnectBtn.classList.remove('active');
            elements.dataBtn.classList.add('inactive');
            elements.dataBtn.classList.remove('active');
        }

        // Submit button
        if (state.isConnected) {
            elements.submitBtn.classList.remove('inactive');
            elements.submitBtn.classList.add('active');
        } else {
            elements.submitBtn.classList.add('inactive');
            elements.submitBtn.classList.remove('active');
        }

        // Shutdown button
        if (state.runningTasks > 0) {
            elements.shutdownBtn.classList.remove('inactive');
            elements.shutdownBtn.classList.add('active');
        } else {
            elements.shutdownBtn.classList.add('inactive');
            elements.shutdownBtn.classList.remove('active');
        }
    }

    // Show toast notification
    function showToast(message, type = 'info') {
        const toast = elements.toast;
        toast.textContent = message;
        toast.className = `toast ${type}`;

        // Force layout recalculation
        toast.offsetHeight;

        toast.classList.add('show');

        setTimeout(() => {
            toast.classList.remove('show');
        }, config.toastDuration);
    }

    // Show loading indicator
    function showLoading() {
        elements.loadingOverlay.style.display = 'block';
        elements.loadingSpinner.style.display = 'block';
    }

    // Hide loading indicator
    function hideLoading() {
        elements.loadingOverlay.style.display = 'none';
        elements.loadingSpinner.style.display = 'none';
    }

    // Handle page visibility changes
    document.addEventListener('visibilitychange', () => {
        if (document.visibilityState === 'visible') {
            // Reconnect and refresh data when page becomes visible again
            if (!state.isConnected && state.socket) {
                connectWebSocket();
            }
            updateTaskCount();
        }
    });

    // Handle page unload
    window.addEventListener('beforeunload', () => {
        // Close socket connection when leaving the page
        if (state.socket) {
            state.socket.close();
        }

        // Clear the interval
        if (state.intervalId) {
            clearInterval(state.intervalId);
        }
    });

    // Initialize the application when DOM is fully loaded
    document.addEventListener('DOMContentLoaded', initApp);
</script>
</body>
</html>